{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python中创建ndarrary的20中方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 一、通过ndarray创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1.1 一维数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = np.array([1, 2, 3])\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1.2 二维数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3, 4],\n",
       "       [2, 3, 4, 5]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.array([[1, 2, 3, 4],\n",
    "       [2, 3, 4, 5]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1.3 三维数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 1  2 32 23]\n",
      "  [23  3 23  3]]\n",
      "\n",
      " [[ 1  2  3  4]\n",
      "  [23  3  4 32]]]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[[ 1,  2, 32, 23],\n",
       "        [23,  3, 23,  3]],\n",
       "\n",
       "       [[ 1,  2,  3,  4],\n",
       "        [23,  3,  4, 32]]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr1 = np.array([\n",
    "    [\n",
    "        [1, 2, 32, 23],\n",
    "        [23, 3, 23, 3]\n",
    "    ],\n",
    "    [\n",
    "        [1, 2, 3, 4],\n",
    "        [23, 3, 4, 32]\n",
    "    ]\n",
    "])\n",
    "print(arr1)\n",
    "print(type(arr1))\n",
    "arr1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 二、创建ndarrary的常见函数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. zeros()函数，指定一个维度元组（形状参数），返回全0的ndarrary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.,  0.]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr2 = np.zeros((2, 4))\n",
    "arr2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 3. ones()函数，指定一个维度元组（形状参数），返回全1的ndarrary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.,  1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.,  1.]])"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr3 = np.ones((4, 4))\n",
    "arr3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 4. empty()函数，指定一个维度元组（形状参数），返回一个值（垃圾值）为被初始化的ndarrary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  7.89119642e-312,   4.22795269e-307],\n",
       "       [  9.34608432e-307,   1.11258854e-306]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr4 = np.empty((2, 2))\n",
    "arr4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 三、其他创建ndarrary的方式"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 5. numpy.arange([start ], stop[, step ], dtype=None)函数，左开右闭"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 2, 3, 4, 5, 6, 7, 8, 9])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr5 = np.arange(1, 10, 1)\n",
    "arr5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 6. numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)函数， 产生一个等差数列，左闭右闭"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.,  1.,  2.,  3.,  4.])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr6 = np.linspace(0, 4, 5)\n",
    "arr6"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 7. numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)函数，底数默认为10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  1.,   2.,   4.,   8.,  16.])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr7 = np.logspace(0, 4, 5, base=2)\n",
    "arr7"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 8. numpy.eye(N, M=None, k=0, dtype=<type ‘float’>)函数，生成NxM的单位矩阵\n",
    "Return a 2-D array with ones on the diagonal and zeros elsewhere."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.,  0.,  0.],\n",
       "       [ 0.,  1.,  0.],\n",
       "       [ 0.,  0.,  1.],\n",
       "       [ 0.,  0.,  0.]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr8 = np.eye(4, 3)\n",
    "arr8"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 9. numpy.zeros_like(a, dtype=None, order=’K’, subok=True)函数，返回一个与a的形状参数一样的元素全部为0的数组\n",
    "Return an array of zeros with the same shape and type as a given array.\n",
    "参数subok,是否继承a的数据类型；\n",
    "参数order，指定返回的结果在内存中的存储布局，默认是'K'，表示尽可能与a相同。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 返回一个与arr8形状应的全0数组\n",
    "arr9 = np.zeros_like(arr8)\n",
    "arr9"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 10. numpy.ones_like(a, dtype=None, order=’K’, subok=True)函数，\n",
    "返回一个与a的形状参数一样且元素全为0的数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.],\n",
       "       [ 1.,  1.,  1.]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 返回一个与ar9形状应的全0数组\n",
    "arr10 = np.ones_like(arr9)\n",
    "arr10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 11. numpy.empty_like(a, dtype=None, order=’K’, subok=True)函数，返回一个与a形状相同且全部值为垃圾值（随机值）的数组\n",
    "Return a new array with the same shape and type as a given array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  7.89102294e-312,   6.27463370e-322,   0.00000000e+000,\n",
       "          0.00000000e+000],\n",
       "       [  8.45593933e-307,   5.30276956e+180,   7.70748458e-043,\n",
       "          4.57487963e-071],\n",
       "       [  3.45618033e-086,   3.35860426e-143,   6.01433264e+175,\n",
       "          6.93885958e+218],\n",
       "       [  5.56218858e+180,   3.94356143e+180,   4.75084178e-037,\n",
       "          1.24689504e-047],\n",
       "       [  3.85156077e-057,   2.06073242e+184,   4.71530148e-143,\n",
       "          1.50008929e+248]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr11 = np.empty_like(np.ones((5,4)))\n",
    "arr11"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 12. numpy.copy(a, order=’K’)函数，返回与a一样的数组\n",
    "Return an array copy of the given object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  1.00000000e+000,   6.27463370e-322,   0.00000000e+000,\n",
       "          0.00000000e+000],\n",
       "       [  8.45593933e-307,   5.30276956e+180,   7.70748458e-043,\n",
       "          4.57487963e-071],\n",
       "       [  3.45618033e-086,   3.35860426e-143,   6.01433264e+175,\n",
       "          6.93885958e+218],\n",
       "       [  5.56218858e+180,   3.94356143e+180,   4.75084178e-037,\n",
       "          1.24689504e-047],\n",
       "       [  3.85156077e-057,   2.06073242e+184,   4.71530148e-143,\n",
       "          1.50008929e+248]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 属于深拷贝，修改复制数组，对原数组没有影响\n",
    "arr12 = np.copy(arr11)\n",
    "arr12[0, 0] = 1\n",
    "arr12"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 13. numpy.identity(n, dtype=None)函数，返回一个n阶单位方阵\n",
    "Return the identity array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 1.,  0.,  0.,  0.],\n",
       "       [ 0.,  1.,  0.,  0.],\n",
       "       [ 0.,  0.,  1.,  0.],\n",
       "       [ 0.,  0.,  0.,  1.]])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr13 = np.identity(4)\n",
    "arr13"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 14. numpy.fromfunction(function, shape, **kwargs)返回一个数组，元素的值由函数计算，形状由shape元组限制\n",
    "注意：参数shape是一个元组，shape元组中的元素个数需要与函数中的参数个数一致，分别表示不同纬度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.  1.  2.]\n",
      " [ 1.  2.  3.]\n",
      " [ 2.  3.  4.]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[[ 0.,  1.,  2.],\n",
       "        [ 1.,  2.,  3.],\n",
       "        [ 2.,  3.,  4.]],\n",
       "\n",
       "       [[ 1.,  2.,  3.],\n",
       "        [ 2.,  3.,  4.],\n",
       "        [ 3.,  4.,  5.]],\n",
       "\n",
       "       [[ 2.,  3.,  4.],\n",
       "        [ 3.,  4.,  5.],\n",
       "        [ 4.,  5.,  6.]]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr20 = np.fromfunction(lambda x, y: x+y, shape=(3, 3))\n",
    "print(arr20)\n",
    "arr21 = np.fromfunction(lambda x, y, z: x+y+z, shape=(3, 3, 3))\n",
    "arr21"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 15. numpy.mgrid函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-1  1]\n",
      "[-1.  3.]\n",
      "[-1  0  1  2]\n",
      "[[[0 0 0 0 0]\n",
      "  [1 1 1 1 1]\n",
      "  [2 2 2 2 2]\n",
      "  [3 3 3 3 3]\n",
      "  [4 4 4 4 4]]\n",
      "\n",
      " [[0 1 2 3 4]\n",
      "  [0 1 2 3 4]\n",
      "  [0 1 2 3 4]\n",
      "  [0 1 2 3 4]\n",
      "  [0 1 2 3 4]]]\n"
     ]
    }
   ],
   "source": [
    "arr14 = np.mgrid[-1:3:2]    # 表示从-1开始，步长为1，取2个数字\n",
    "print(arr14)\n",
    "arr15 = np.mgrid[-1:3:2j]  # 当加'j'时，表示左闭右闭，且取到2个数字\n",
    "print(arr15)\n",
    "arr16 = np.mgrid[-1:3]    # 当指定两个参数时，功能与numpy.arange()函数一样\n",
    "print(arr16)\n",
    "arr18 = np.mgrid[0:5, 0:5] # 分别在两个维度上做填充\n",
    "print(arr18)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  16. numpy.ogrid函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\n",
      "[array([[0],\n",
      "       [1],\n",
      "       [2],\n",
      "       [3],\n",
      "       [4]]), array([[0, 1, 2, 3, 4]])]\n"
     ]
    }
   ],
   "source": [
    "arr19 = np.ogrid[1:2]\n",
    "print(arr19)\n",
    "arr20 = np.ogrid[0:5, 0:5]\n",
    "print(arr20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  17. numpy.fromstring(string, dtype=float, count=-1, sep=’‘)函数，从字符串创建一个一维ndarrary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.,  2.,  3.,  4.])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr21 = np.fromstring('1 2 3 4', sep=' ')\n",
    "arr21"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 18. numpy.fromiter(iterable, dtype, count=-1)函数，返回一个一维数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0.,  1.,  4.,  9.])"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 需要指定数据类型dtype\n",
    "iterable = (i*i for i in range(4))\n",
    "arr22 = np.fromiter(iterable,dtype=float)\n",
    "arr22"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 四、其他方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 19. numpy.fromfile(file, dtype=float, count=-1, sep=’‘)函数，从文本文件或二进制文件中创建ndarrary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 20. numpy.loadtxt(fname, dtype=<type ‘float’>, comments=’#’, delimiter=None, converters=None,skiprows=0, usecols=None, unpack=False, ndmin=0)从文件中创建"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
